home *** CD-ROM | disk | FTP | other *** search
- Path: Thomas.generics.co.uk!usenet
- From: Rob Stenton <rws@metagen.co.uk>
- Newsgroups: comp.lang.c
- Subject: Re: accessing structures (newbie question)
- Date: Mon, 19 Feb 1996 14:32:00 -0800
- Organization: MediaWell Ltd.
- Message-ID: <3128FA60.5227@metagen.co.uk>
- References: <4g8gic$o6u@news1.sunbelt.net>
- NNTP-Posting-Host: 194.216.45.117
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0b6b (Win16; I)
-
- dking@SunBelt.Net wrote:
- >
- > Ok. having trouble accessing structure.
-
- There are basically two ways of accessing elements within a malloced
- buffer:
- 1. Treat the malloced buffer as an array (as you suggested).
- 2. Increment a local pointer by sizeof(picture) in loop iteration.
-
- The first method is preferable because the second method involves pointer
- arithmetic (always best avoided) which can cause problems on different
- memory architectures and assumes things about BYTE sizes (but usually
- works).
-
- I think you may have been using the wrong syntax when you tried the array
- method. The xth item is given by 'photos[x].' which is equivalent to
- '(photos + x * sizeof(picture))->'.
-
- The two ways for solving this problem are therefore:
- 1. (Recommended)
- for (x=0;x<num_of_files;x++)
- {
- strncpy(photos[x].filename, filelist[x],12);
- strncpy(photos[x].diskname, inputdisk,12);
- strncpy(photos[x].indexname, inputindex,12);
- }
- or
- 2. (Not recommended)
- for (x=0;x<num_of_files;x++)
- {
- strncpy((photos + x * sizeof(picture))->filename,
- filelist[x],12);
- strncpy((photos + x * sizeof(picture))->diskname,
- inputdisk,12);
- strncpy((photos + x * sizeof(picture))->indexname,
- inputindex,12);
- }
-
- Perhaps you were confusing the use of '.' and '->' when you tried this
- yourself. If you understand the use of '.' and '->' in the above
- solutions I think you will have this licked !
- Rob
-